package ema.tpjee.banking.dao.local;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ema.tpjee.banking.dao.CityDao;
import ema.tpjee.banking.model.City;



public class CityDaoImpl implements CityDao, Serializable {
	

	private static final long serialVersionUID = -3515075296720539959L;
	
	
	private List<City> cities = new ArrayList<City>();

	public City add(City c) {
		this.cities.add(c);
		return c;
	}
	
	public City create() {
		City c = new City();
		c.setName("noname");
		return add(c);
	}

	public City delete(City c) {
		City result = null;
		City f = find(c);
		if (f != null) {
			result = prior(c);
			if (result == null)
				result = next(c);
			this.cities.remove(c);
		}
		return result;
	}

	public City find(int id) {
		for (Iterator<City> i = this.cities.iterator(); i.hasNext();) {
			City b = i.next();
			if (b.getId() == id)
				return b;
		}
		return null;
	}

	public City find(City c) {
		return find(c.getId());
	}

	/**
	 * retourne la premi�re City correspondant au code postal pass� en param�tre
	 */
	public City find(String zipcode) {
		for (Iterator<City> i = this.cities.iterator(); i.hasNext();) {
			City b = i.next();
			if (b.getZipCode().equals(zipcode))
				return b;
		}
		return null;
	}

	public City first() {
		return getList().get(0);
	}

	
	public List<City> getList() {
		return this.cities;
	}

	public City last() {
		List<City> cities = getList();
		return cities.get(cities.size() - 1);
	}

	public City merge(City c) {
		City f = find(c);
		f.setCountry(c.getCountry());
		f.setName(c.getName());
		f.setZipCode(c.getZipCode());
		return f;
	}

	public List<City> populate() {
		City c1 = new City("N�mes", "30000", "France");
		add(c1);
		City c2 = new City("Montpellier", "34000", "France");
		add(c2);
		City c3 = new City("Al�s", "30000", "France");
		add(c3);
		return getList();
	}

	public City prior(City c) {
		return Paging.prior(getList(), c);
	}
	
	public City next(City c) {
		return Paging.next(getList(), c);
	}

	public Boolean isSame(City a, City b) {
		return a!=null && b!=null && a.getId() == b.getId();
	}

}
